//
//  ClipContentView.m
//  TheVideoClip
//
//  Created by 北斗君合MacMini on 2018/3/30.
//  Copyright © 2018年 北斗君合MacMini. All rights reserved.
//

#import "ClipContentView.h"

#import "JLDoubleSlider.h"

#import "ClipViewModel.h"

#import <CoreLocation/CoreLocation.h>

@interface ClipContentView () <UITextFieldDelegate> {
    CGFloat _imageViewSize;
    CGFloat _imageViewTopMargin;
    CGFloat _imageViewLeftMargin;
    CGFloat _inputButtonTopMargin;
    CGFloat _inputButtonWidth;
    CGFloat _inputButtonHeight;
    CGFloat _textFieldWidth;
    CGFloat _textFieldHeight;
    CGFloat _textFieldTopMargin;
    CGFloat _alertLabelTopMargin;
    CGFloat _cutSliderWidth;
    CGFloat _cutSliderHeight;
    CGFloat _cutSliderTopMargin;
    
    CGFloat _inputButtonFontSize;
    CGFloat _alertLabelFontSize;
    CGFloat _textFieldFontSize;
}

@property (nonatomic, strong) UIImageView *bigImageView;

@property (nonatomic, strong) UIView *backMaskView;

@property (nonatomic, strong) UIImageView *startImageView;

@property (nonatomic, strong) UIImageView *endImageView;

@property (nonatomic, strong) UIButton *inputVideoButton;

@property (nonatomic, strong) UITextField *startTextField;

@property (nonatomic, strong) UILabel *alertLabel;

@property (nonatomic, strong) UITextField *endTextField;

@property (nonatomic, strong) JLDoubleSlider *cutSlider;

@property (nonatomic, strong) AVURLAsset *videoAsset;

@property (nonatomic, assign) CGFloat totalTime;

@property (nonatomic, assign) CGFloat minTimeValue;

@property (nonatomic, assign) CGFloat maxTimeValue;

@end

@implementation ClipContentView

- (instancetype)init {
    if (self = [super init]) {
        
        _imageViewTopMargin = 20;
        _imageViewLeftMargin = 20;
        _imageViewSize = (kScreen_Width - _imageViewLeftMargin * 3) * 0.5;
        _inputButtonTopMargin = 40;
        _inputButtonWidth = 250;
        _inputButtonHeight = 45;
        _textFieldWidth = 95;
        _textFieldHeight = 30;
        _textFieldTopMargin = 15;
        _alertLabelTopMargin = 30;
        _cutSliderWidth = kScreen_Width - 2 * _imageViewLeftMargin;
        _cutSliderHeight = 40;
        _cutSliderTopMargin = 25;
        
        _inputButtonFontSize = 17;
        _alertLabelFontSize = 15;
        _textFieldFontSize = 14;
        
        self.backgroundColor = [UIColor whiteColor];
        
        if (!_bigImageView) {
            _bigImageView = [[UIImageView alloc] init];
            _bigImageView.contentMode = UIViewContentModeScaleAspectFit;
            [self addSubview:_bigImageView];
            [_bigImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(self);
            }];
        }
        if (!_backMaskView) {
            _backMaskView = [CreateControlTool getViewWithBackgroundColor:[UIColor blackColor]];
            _backMaskView.alpha = 0.6;
            [self addSubview:_backMaskView];
            [_backMaskView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(self);
            }];
        }
        if (!_startImageView) {
            _startImageView = [[UIImageView alloc] init];
            _startImageView.backgroundColor = [UIColor blackColor];
            [self addSubview:_startImageView];
            [_startImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self).offset(_imageViewTopMargin);
                make.left.equalTo(self).offset(_imageViewLeftMargin);
                make.width.height.mas_equalTo(_imageViewSize);
            }];
        }
        if (!_endImageView) {
            _endImageView = [[UIImageView alloc] init];
            _endImageView.backgroundColor = [UIColor blackColor];
            [self addSubview:_endImageView];
            [_endImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self).offset(_imageViewTopMargin);
                make.right.equalTo(self).offset(-_imageViewLeftMargin);
                make.width.height.mas_equalTo(_imageViewSize);
            }];
        }
        if (!_inputVideoButton) {
            _inputVideoButton = [CreateControlTool getButtonWithNormalTitle:@"导入视频" normalTitleColor:[UIColor whiteColor] fontSize:_inputButtonFontSize target:self action:@selector(inputVideoClick)];
            [_inputVideoButton setBackgroundColor:[CommonMethodTool getRandomColorWithAlpha:0.8]];
            [self addSubview:_inputVideoButton];
            [_inputVideoButton mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self);
                make.top.equalTo(_startImageView.mas_bottom).offset(_inputButtonTopMargin);
                make.width.mas_equalTo(_inputButtonWidth);
                make.height.mas_equalTo(_inputButtonHeight);
            }];
        }
        if (!_alertLabel) {
            _alertLabel = [CreateControlTool getLabelWithText:@"时间输入格式：XX:XX:XX 或 XX:XX" textColor:[UIColor whiteColor] fontSize:_alertLabelFontSize];
            [self addSubview:_alertLabel];
            [_alertLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_startImageView);
                make.top.equalTo(_inputVideoButton.mas_bottom).offset(_alertLabelTopMargin);
            }];
        }
        if (!_startTextField) {
            [self getTextFieldWithAlertText:@"开始：" action:@selector(endEditCutTimeClick:) block:^(UITextField *textField, CGFloat width) {
                _startTextField = textField;
                [self addSubview:_startTextField];
                [_startTextField mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(_startImageView);
                    make.top.equalTo(_alertLabel.mas_bottom).offset(_textFieldTopMargin);
                    make.height.mas_equalTo(_textFieldHeight);
                    make.width.mas_equalTo(_textFieldWidth + width);
                }];
            }];
        }
        if (!_endTextField) {
            [self getTextFieldWithAlertText:@"结束：" action:@selector(endEditCutTimeClick:) block:^(UITextField *textField, CGFloat width) {
                _endTextField = textField;
                [self addSubview:_endTextField];
                [_endTextField mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.equalTo(_endImageView);
                    make.top.equalTo(_startTextField);
                    make.height.mas_equalTo(_textFieldHeight);
                    make.width.mas_equalTo(_textFieldWidth + width);
                }];
            }];
        }
        if (!_cutSlider) {
            _cutSlider = [[JLDoubleSlider alloc] initWithFrame:CGRectMake(0, 0, _cutSliderWidth, _cutSliderHeight)];
            _cutSlider.minNum = 0;
            _cutSlider.maxNum = 100;
            _cutSlider.minTintColor = [UIColor redColor];
            _cutSlider.maxTintColor = [UIColor blueColor];
            _cutSlider.mainTintColor = [UIColor blackColor];
            [self addSubview:_cutSlider];
            [_cutSlider mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_startImageView);
                make.top.equalTo(_startTextField.mas_bottom).offset(_cutSliderTopMargin);
                make.width.mas_equalTo(_cutSliderWidth);
                make.height.mas_equalTo(_cutSliderHeight);
            }];
            
            __weak typeof (self) weakSelf = self;
            _cutSlider.minSliderValueChangedBlock = ^(CGFloat minValue) {
                UIImage *startImage = [ClipViewModel getVideoPreViewImageWithTime:minValue asset:weakSelf.videoAsset];
                weakSelf.startImageView.image = startImage;
                weakSelf.bigImageView.image = startImage;
                weakSelf.startTextField.text = [ClipViewModel timeFormatted:minValue];
                weakSelf.minTimeValue = minValue;
            };
            _cutSlider.maxSliderValueChangedBlock = ^(CGFloat maxValue) {
                UIImage *endImage = [ClipViewModel getVideoPreViewImageWithTime:maxValue asset:weakSelf.videoAsset];
                weakSelf.endImageView.image = endImage;
                weakSelf.bigImageView.image = endImage;
                weakSelf.endTextField.text = [ClipViewModel timeFormatted:maxValue];
                weakSelf.maxTimeValue = maxValue;
            };
        }
        _cutSlider.userInteractionEnabled = _startTextField.userInteractionEnabled = _endTextField.userInteractionEnabled = NO;
    }
    return self;
}

- (void)getTextFieldWithAlertText:(NSString *)alertText action:(SEL)action block:(void(^)(UITextField *textField, CGFloat width))block {
    UITextField *textField = [CreateControlTool getTextFieldWithTextFontSize:_textFieldFontSize textColor:[UIColor whiteColor] placeholder:@"可输入时间"];
    textField.returnKeyType = UIReturnKeyDone;
    textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    textField.delegate = self;
    [textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    UILabel *alertLabel = [CreateControlTool getLabelWithText:alertText textColor:[UIColor whiteColor] fontSize:_textFieldFontSize];
    CGFloat width = [CommonMethodTool getTextWidthWithFont:_textFieldFontSize text:alertLabel.text];
    alertLabel.frame = CGRectMake(0, 0, width, _textFieldHeight);
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.leftView = alertLabel;
    [textField addTarget:self action:action forControlEvents:UIControlEventEditingDidEnd];
    block(textField, width);
}

- (void)inputVideoClick {
    if (_inputVideoBlock) {
        _inputVideoBlock();
    }
}

- (void)completeInputVieo:(PHAsset *)asset {
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        NSURL *fileRUL = [asset valueForKey:@"URL"];
        //转码配置
        _videoAsset = [AVURLAsset URLAssetWithURL:fileRUL options:nil];
        UIImage *startImage = [ClipViewModel getVideoPreViewImageWithTime:0 asset:_videoAsset];
        CMTime time = [_videoAsset duration];
        _totalTime = time.value / time.timescale;
        UIImage *endImage = [ClipViewModel getVideoPreViewImageWithTime:_totalTime asset:_videoAsset];
        dispatch_async(dispatch_get_main_queue(), ^{
            _cutSlider.userInteractionEnabled = _startTextField.userInteractionEnabled = _endTextField.userInteractionEnabled = YES;
            _startImageView.image = startImage;
            _bigImageView.image = startImage;
            _endImageView.image = endImage;
            _startTextField.text = @"00:00";
            _endTextField.text = [ClipViewModel timeFormatted:_totalTime];
            _cutSlider.maxNum = _totalTime;
            _minTimeValue = 0;
            _maxTimeValue = _totalTime;
        });
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self endEditCutTimeClick:textField];
    return YES;
}

- (void)endEditCutTimeClick:(UITextField *)textField {
    if (textField.text.length != 5 && textField.text.length != 8) {
        [MBProgressHUD showToast:@"输入时间格式有误" view:self];
        return;
    }
    NSArray *array = [textField.text componentsSeparatedByString:@":"];
    for (NSString *string in array) {
        if (string.length != 2 || ![string isPureInt] || [string intValue] >= 60 || [string integerValue] < 0) {
            [MBProgressHUD showToast:@"输入时间格式有误" view:self];
            return;
        }
    }
    if ([textField isEqual:_startTextField]) {
        CGFloat minTimeValue = [ClipViewModel realSecondsWithFormatted:textField.text];
        if (minTimeValue >= _maxTimeValue) {
            [MBProgressHUD showToast:@"开始时间需小于结束时间" view:self];
            return;
        }
        _minTimeValue = minTimeValue;
        UIImage *startImage = [ClipViewModel getVideoPreViewImageWithTime:_minTimeValue asset:_videoAsset];
        _startImageView.image = startImage;
        _bigImageView.image = startImage;
        _cutSlider.currentMinValue = _minTimeValue;
    } else if ([textField isEqual:_endTextField]) {
        CGFloat maxTimeValue = [ClipViewModel realSecondsWithFormatted:textField.text];
        if (maxTimeValue <= _minTimeValue) {
            [MBProgressHUD showToast:@"结束时间需大于开始时间" view:self];
            return;
        }
        _maxTimeValue = maxTimeValue;
        UIImage *endImage = [ClipViewModel getVideoPreViewImageWithTime:_maxTimeValue asset:_videoAsset];
        _endImageView.image = endImage;
        _bigImageView.image = endImage;
        _cutSlider.currentMaxValue = _maxTimeValue;
    }
    [textField resignFirstResponder];
}

- (void)saveCutVideoClick {
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == kCLAuthorizationStatusRestricted || author == kCLAuthorizationStatusDenied){
        //无权限
        [MBProgressHUD showToast:@"请开启访问相册的权限" view:self];
        return;
    }
    [MBProgressHUD showHUDAddedTo:self animated:YES];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ClipViewModel cutVideoAndOutPut:_videoAsset beginTime:_minTimeValue endTime:_maxTimeValue block:^(NSString *videoFilePath, BOOL success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideAllHUDsForView:self animated:YES];
                if (success && videoFilePath) {
                    if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(videoFilePath)) {
                        //保存相册核心代码
                        UISaveVideoAtPathToSavedPhotosAlbum(videoFilePath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
                    }
                }
            });
        }];
    });
}

//保存视频完成之后的回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (error) {
        [MBProgressHUD showToast:@"保存失败" view:self];
        NSLog(@"保存视频失败%@", error.localizedDescription);
    } else {
        [MBProgressHUD showToast:@"保存成功" view:self];
    }
}

@end
